﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.IO;

namespace KGDownload
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        //声明全局变量
        string gvcode;
        string gvsubcode;
        string gvmessage;
        string gvmdefault;

        string gvcover; //歌曲封面图片
        string gvsong_name;//歌曲名称
        string gvsinger_name;//歌曲原唱
        string gvuid;//友友id
        string gvnick;//友友名字
        string gvlevel;//友友等级
        string gvhc_uid;//合唱友友id
        string gvhc_nick;//合唱友友名字
        string gvhc_level;//合唱友友等级
        string gvscore;//系统评分
        string gvplay_num;//播放次数
        string gvgift_num;//收获K币
        string gvscoreRank;//系统评级
        string gvcomment_num;//歌曲评论
        string gvflower_num;//收获鲜花
        string gvctime;//发布时间
        string gvplayurl;//音频下载url
        string gvplayurl_video;//视频下载url

        string NewFileName;//下载文件文件名

        private void Form1_Load(object sender, EventArgs e)
        {


            //http://kg.qq.com/share.html?s=dqwt4z04gzKE
        }

        private void btn_GetJsonData_Click(object sender, EventArgs e)
        {
            if (txt_shareURL.Text == "")
            {
                MessageBox.Show("友友，以你的聪明才智，怎么会忘记填写分享地址了呢...", "快快填写分享地址吧！");
                txt_shareURL.Focus();
                return;
            }

            //清理全局变量
            gvcode = "";
            gvsubcode = "";
            gvmessage = "";
            gvmdefault = "";

            gvcover = ""; //歌曲封面图片
            gvsong_name = "";//歌曲名称
            gvsinger_name = "";//歌曲原唱
            gvuid = "";//友友id
            gvnick = "";//友友名字
            gvlevel = "";//友友等级
            gvhc_uid = "";//合唱友友id
            gvhc_nick = "";//合唱友友名字
            gvhc_level = "";//合唱友友等级
            gvscore = "";//系统评分
            gvplay_num = "";//播放次数
            gvgift_num = "";//收获K币
            gvscoreRank = "";//系统评级
            gvcomment_num = "";//歌曲评论
            gvflower_num = "";//收获鲜花
            gvctime = "";//发布时间
            gvplayurl = "";//下载url

            prog_download.Value = 0;
            txtlabel.Text = "-";

            lbl_SongNameStr.Text = "-";
            lbl_SingerNameStr.Text = "-";

            lbl_NickNameStr.Text = "-";
            lbl_LevelStr.Text = "-";

            lbl_hcNickNameStr.Text = "-";
            lbl_hcLevelStr.Text = "-";

            lbl_ScoreStr.Text = "-";
            lbl_PlayNumStr.Text = "-";
            lbl_GiftNumStr.Text = "-";
            lbl_ScoreRankStr.Text = "-";
            lbl_CommentNumStr.Text = "-";
            lbl_FlowerNumStr.Text = "-";
            lbl_CreateTimeStr.Text = "-";
            


            string KGMusicShareURL;
            string txtInputStr = txt_shareURL.Text;

            if (txtInputStr.Length == 12)
            {
                KGMusicShareURL = txtInputStr;
            }
            else
            {
                try
                {
                    KGMusicShareURL = smsindexOf(txtInputStr, "s");
                }
                catch
                {
                    MessageBox.Show("网址不正确哟！");
                    txt_shareURL.Text = "";
                    return;
                }
            }

            string GetMusicInfoUrlStr = @"http://cgi.kg.qq.com/fcgi-bin/kg_ugc_getdetail?callback=jsopgetsonginfo&inCharset=GB2312&outCharset=utf-8&format=&g_tk=1741551592&g_tk_openkey=1093518604&nocache=0.42761945142410696&v=4&shareid=" + KGMusicShareURL + "&_=1482920012053";
            string JsonStr = HttpHelper.GetResponseString(HttpHelper.CreateGetHttpResponse(GetMusicInfoUrlStr, 15000, ""));
            JsonStr = JsonStr.Remove(JsonStr.Length - 1, 1);
            JsonStr = JsonStr.Replace("jsopgetsonginfo(", "");
            MusicData md = JsonConvert.DeserializeObject<MusicData>(JsonStr);



            //为全局变量赋值
            gvcode = md.code;
            gvsubcode = md.subcode;
            gvmessage = md.message;
            gvmdefault = md.mdefault;

            gvcover = md.data.cover; //歌曲封面图片
            gvsong_name = md.data.song_name;//歌曲名称
            gvsinger_name = md.data.singer_name;//歌曲原唱
            gvuid = md.data.uid;//友友id
            gvnick = md.data.nick;//友友名字
            gvlevel = md.data.level;//友友等级
            gvhc_uid = md.data.hc_uid;//合唱友友id
            gvhc_nick = md.data.hc_nick;//合唱友友名字
            gvhc_level = md.data.hc_level;//合唱友友等级
            gvscore = md.data.score;//系统评分
            gvplay_num = md.data.play_num;//播放次数
            gvgift_num = md.data.gift_num;//收获K币
            gvscoreRank = md.data.scoreRank;//系统评级
            gvcomment_num = md.data.comment_num;//歌曲评论
            gvflower_num = md.data.flower_num;//收获鲜花
            gvctime = md.data.ctime;//发布时间
            gvplayurl = md.data.playurl;//音频下载url
            gvplayurl_video = md.data.playurl_video;//视频下载url
            if (gvhc_nick == "")
            {
                NewFileName = gvsong_name + "-" + gvnick;
            }
            else
            {
                NewFileName = gvsong_name + "-" + gvnick + "_" + gvhc_nick;
            }
            if (gvcode != "0")
            {
                MessageBox.Show("歌曲信息获取失败 " + gvmessage + "\r现在唯一能做的，重新复制下网址试试·", "悲剧了...");
                //清理全局变量
                gvcode = "";
                gvsubcode = "";
                gvmessage = "";
                gvmdefault = "";

                gvcover = ""; //歌曲封面图片
                gvsong_name = "";//歌曲名称
                gvsinger_name = "";//歌曲原唱
                gvuid = "";//友友id
                gvnick = "";//友友名字
                gvlevel = "";//友友等级
                gvhc_uid = "";//合唱友友id
                gvhc_nick = "";//合唱友友名字
                gvhc_level = "";//合唱友友等级
                gvscore = "";//系统评分
                gvplay_num = "";//播放次数
                gvgift_num = "";//收获K币
                gvscoreRank = "";//系统评级
                gvcomment_num = "";//歌曲评论
                gvflower_num = "";//收获鲜花
                gvctime = "";//发布时间
                gvplayurl = "";//下载url
                gvplayurl_video = "";

                return;
            }
            //绑定控件
            pic_MusicCover.ImageLocation = gvcover;

            lbl_SongNameStr.Text = gvsong_name;
            lbl_SingerNameStr.Text = gvsinger_name;

            lbl_NickNameStr.Text = emReplace(gvnick);
            lbl_LevelStr.Text = getLevelName(gvlevel);

            if (gvhc_nick == "")
            {
                lbl_hcNickNameStr.Text = "-";
                lbl_hcLevelStr.Text = "-";
            }
            else
            {
                lbl_hcNickNameStr.Text = emReplace(gvhc_nick);
                lbl_hcLevelStr.Text = getLevelName(gvhc_level);
            }

            lbl_ScoreStr.Text = gvscore;
            lbl_PlayNumStr.Text = gvplay_num;
            lbl_GiftNumStr.Text = gvgift_num;
            lbl_ScoreRankStr.Text = getScoreRank(gvscoreRank);
            lbl_CommentNumStr.Text = gvcomment_num;
            lbl_FlowerNumStr.Text = gvflower_num;

            DateTime createDT;
            createDT = GetTime(gvctime);
            lbl_CreateTimeStr.Text = createDT.ToString();

            btn_download.Enabled = true;

        }
        public class MusicData
        {
            public string code;
            public string subcode;
            public string message;
            public string mdefault;

            public struct musicdata
            {
                public string cover; //歌曲封面图片

                public string song_name;//歌曲名称
                public string singer_name;//歌曲原唱

                public string uid; //友友ID
                public string nick;//友友名字
                public string level;//友友等级

                public string hc_uid;//合唱友友ID
                public string hc_nick;//合唱友友名字
                public string hc_level;//合唱友友等级

                public string score;//系统评分
                public string play_num;//播放次数
                public string gift_num;//收获K币

                public string scoreRank;//系统评级
                public string comment_num;//歌曲评论
                public string flower_num;//收获鲜花

                public string ctime;//发布时间

                public string playurl;//音频下载url
                public string playurl_video;//视频下载url

            }
            public musicdata data;

            //构造函数
            public MusicData()
            {
                code = "0";
                subcode = "0";
                message = "";
                mdefault = "0";

                data.cover = "";
                data.song_name = "";
                data.singer_name = "";
                data.uid = "";
                data.nick = "";
                data.level = "0";
                data.hc_uid = "";
                data.hc_nick = "";
                data.hc_level = "0";
                data.score = "0";
                data.play_num = "0";
                data.gift_num = "0";
                data.scoreRank = "0";
                data.comment_num = "0";
                data.flower_num = "0";
                data.ctime = "0";
                data.playurl = "";

            }
        }

        /// <summary>
        /// 过滤昵称中的表情符号
        /// </summary>
        /// <param name="emString"></param>
        /// <returns></returns>
        private string emReplace(string emString)
        {
            emString = Regex.Replace(emString, @"[em].*?[/em]", "", RegexOptions.IgnoreCase);
            emString = emString.Replace("[", "");
            emString = emString.Replace("]", "");
            return emString;
        }
        /// <summary>
        /// 下载方法
        /// </summary>
        /// <param name="URL">分享URL</param>
        /// <param name="filename">保存路径文件名默认保存在当前软件运行目录</param>
        /// <param name="prog">进度条</param>
        /// <param name="label1">进度提示</param>
        public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label ProgLabel)
        {
            float percent = 0;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);

                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    if (percent <= 99)
                    {
                        ProgLabel.Text = "正在下载请稍候！" + percent.ToString() + "%";
                    }
                    else {
                        ProgLabel.Text = "已完成下载 " + percent.ToString() + "%";
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }




        /// <summary>
        /// 截取URL参数
        /// </summary>
        /// <param name="sourceStr"></param>
        /// <param name="strOf"></param>
        /// <returns></returns>
        private string smsindexOf(string sourceStr, string strOf)
        {
            sourceStr = sourceStr.Substring(sourceStr.IndexOf(strOf + "="), sourceStr.Length - sourceStr.IndexOf(strOf + "="));
            sourceStr = sourceStr + "&";
            sourceStr = sourceStr.Substring(sourceStr.IndexOf("=") + 1, sourceStr.IndexOf("&") - sourceStr.IndexOf("=") - 1);
            return sourceStr;
        }

        /// <summary>
        /// 获取评级
        /// </summary>
        /// <param name="sRank"></param>
        /// <returns></returns>
        private string getScoreRank(string sRank)
        {
            switch (sRank)
            {
                case "1":
                    return "C";
                case "2":
                    return "B";
                case "3":
                    return "A";
                case "4":
                    return "S";
                case "5":
                    return "SS";
                case "6":
                    return "SSS";
                default:
                    return "-";
            }
        }

        /// <summary>
        /// 等级名称
        /// </summary>
        /// <param name="Lv">等级</param>
        /// <returns>等级名称</returns>
        private string getLevelName(string Lv)
        {
            switch (Lv)
            {
                case "1":
                    return Lv + "级【新晋歌艺学徒】";
                case "2":
                    return Lv + "级【进阶歌艺学徒】";
                case "3":
                    return Lv + "级【实力歌艺学徒】";
                case "4":
                    return Lv + "级【新晋选秀歌手】";
                case "5":
                    return Lv + "级【进阶选秀歌手】";
                case "6":
                    return Lv + "级【实力选秀歌手】";
                case "7":
                    return Lv + "级【新晋闪亮明星】";
                case "8":
                    return Lv + "级【进阶闪亮明星】";
                case "9":
                    return Lv + "级【超级闪亮明星】";
                case "10":
                    return Lv + "级【新晋人气偶像】";
                case "11":
                    return Lv + "级【进阶人气偶像】";
                case "12":
                    return Lv + "级【超级人气偶像】";
                case "13":
                    return Lv + "级【新晋实力唱将】";
                case "14":
                    return Lv + "级【进阶实力唱将】";
                case "15":
                    return Lv + "级【超级实力唱将】";
                case "16":
                    return Lv + "级【新晋当红明星】";
                case "17":
                    return Lv + "级【进阶当红明星】";
                case "18":
                    return Lv + "级【超级当红明星】";
                case "19":
                    return Lv + "级【新晋天王巨星】";
                case "20":
                    return Lv + "级【进阶天王巨星】";
                case "21":
                    return Lv + "级【超级天王巨星】";
                default:
                    return "-";
            }
        }

        private void btn_download_Click(object sender, EventArgs e)
        {

            //音频
            if (gvplayurl != "")
            {
                if (!Directory.Exists(System.Windows.Forms.Application.StartupPath + "\\下载的歌曲文件\\"))//若文件夹不存在则新建文件夹   
                {
                    Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + "\\下载的歌曲文件\\"); //新建文件夹   
                }
                DownloadFile(gvplayurl, System.Windows.Forms.Application.StartupPath + "\\下载的歌曲文件\\" + NewFileName + ".m4a", prog_download, txtlabel);
            }
            //视频
            if (gvplayurl_video != "")
            {
                if (!Directory.Exists(System.Windows.Forms.Application.StartupPath + "\\下载的视频文件\\"))//若文件夹不存在则新建文件夹   
                {
                    Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + "\\下载的视频文件\\"); //新建文件夹   
                }
                DownloadFile(gvplayurl_video, System.Windows.Forms.Application.StartupPath + "\\下载的视频文件\\" + NewFileName + ".mp4", prog_download, txtlabel);
            }


        }



        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        private void lbl_hcNickNameStr_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (gvhc_uid.Length > 10)
            {
                Process.Start("http://kg.qq.com/node/personal?uid=" + gvhc_uid + "");
            }
            else
            {
                return;
            }
        }

        private void lbl_NickNameStr_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (gvuid != "")
            {
                Process.Start("http://kg.qq.com/node/personal?uid=" + gvuid + "");
            }
            else
            {
                return;
            }


        }
    }
}
